<template>
  <!-- 添加局部容器，并监听滚动事件 -->
  <div ref="scrollContainer" class="scroll-container" @scroll="handleScroll">
    <div grid grid-cols-3 gap-46px px-72px>
      <div v-for="item in dataList" :key="item.id" @click="emit('click', item.id)">
        <img :src="item.goodsImgStr.split(',')[0]" rounded-20px w-240px h-240px alt="商品图片" />
        <div text-36px line-clamp-1>{{ item.goodsName }}</div>
        <div text-28px text="#7D7D7D">
          兑换积分:
          <span text-36px text="#FF0000">{{ item.needPoints }}</span>
        </div>
      </div>
    </div>

    <!-- 加载提示 -->
    <div v-if="loading" class="loading-text">加载中...</div>
    <div v-if="finished && dataList.length !== 0" class="finished-text">没有更多了</div>

    <div v-if="!loading && dataList.length === 0" class="flex flex-col items-center py-40px">
      <img src="@/assets/images/empty.png" alt="无数据" class="w-300px h-300px" />
      <div class="text-38px mt-20px text-[#999]">无数据</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { goodsList } from '@/api/index'
const router = useRouter()
const props = defineProps({
  points: String,
  type: String
})
// emits
const emit = defineEmits(['click'])

// 添加滚动容器的 ref
const scrollContainer = ref(null)
const dataList = ref([])
const loading = ref(false)
const finished = ref(false)
const pageNo = ref(1)
const pageSize = 10

// 滚动事件处理
const handleScroll = () => {
  const container = scrollContainer.value
  if (
    container.scrollTop + container.clientHeight >= container.scrollHeight - 50 &&
    !loading.value &&
    !finished.value
  ) {
    loadMore()
  }
}

const loadMore = async () => {
  if (finished.value) return
  loading.value = true
  try {
    const res = await goodsList({
      pageNum: pageNo.value,
      pageSize: pageSize,
      queryData: props.type === 'keduihuan' ? props.points : null
    })

    if (res.data && res.data.length > 0) {
      dataList.value = [...dataList.value, ...res.data]
      pageNo.value++
    } else {
      finished.value = true
    }
  } catch (error) {
    finished.value = true
  }
  loading.value = false
}

// 监听points变化
watch(
  () => props.points,
  (newValue, oldValue) => {
    if (newValue && newValue !== oldValue) {
      loadMore()
    }
  },
  { immediate: false }
)

onMounted(() => {
  loadMore()
})
</script>

<style scoped>
/* 新增局部容器样式 */
.scroll-container {
  height: 900px; /* 设置容器高度 */
  overflow-y: auto; /* 启用垂直滚动 */
}

.loading-text,
.finished-text {
  text-align: center;
  padding: 20px;
  font-size: 28px;
  color: #666;
}
</style>
<style>
::-webkit-scrollbar {
  width: 0px;
  height: 0px;
}
.nut-empty__description {
  font-size: 38px;
}
</style>
